#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct _client
{
	char id[9];
	char phone[12];
} Client;
typedef struct _short_client
{
	unsigned char short_id[4];
	unsigned char short_phone[5];
} Short_client;

void print_binary(char c)
{
	int i;
	int mask;

	for (i = 7; i >= 0; i--)
	{
		mask = 1 << i;
		putchar((c & mask) ? '1' : '0');
		if (i % 4 == 0)
			putchar(' ');
	}
	putchar(' ');
}

Short_client convert(Client c)
{
	Short_client ret;
	unsigned char temp, bin;
	for(int i=0;i<8;i+=2)
	{
		temp = c.id[i] - '0';
		bin = c.id[i+1] - '0';
		print_binary(temp);
		print_binary(bin);
		printf("%d\n", (i%2)*4);

		ret.short_id[i/2] = temp | bin << 4;
	}
	printf("\n");
	print_binary(ret.short_id[0]);
	print_binary(ret.short_id[1]);
	print_binary(ret.short_id[2]);
	print_binary(ret.short_id[3]);
	printf("\n");

	for(int i=0;i<11;i+=2)
	{
		temp = c.phone[i];
		bin = c.phone[i+1];
		ret.short_phone[i/2] = temp | bin << 4;
	}

	return ret;
}

Short_client *createShortClientArr(int n)
{
	Client *get;
	Short_client *ret;

	get = malloc(sizeof(Client) * n);
	for(int i=0;i<n;i++)
	{
		gets(get[i].id);
		gets(get[i].phone);
	}
	ret = malloc(sizeof(Short_client) * n);
	for(int i=0;i<n;i++)
		ret[i] = convert(get[i]);

	return ret;

}


char *searchClientByID(Short_client *arr, int n, char id[9])
{
	char short_id[4];
	char *ret;
	unsigned char temp, bin;
	int j;
	for(int i=0;i<8;i++)
	{
		temp = id[i];
		bin = id[i+1];
		short_id[i/2] = temp | bin << 4;
	}
	for(j=0;j<n;j++)
		if(strcmp((char *)arr[j].short_id, (char *)short_id) == 0) break;
	if(j>=n) return NULL;
	ret = malloc(sizeof(char) * 12);
	ret[11] = '\0';
	for(int i=0;i<11;i+=2)
	{
		ret[i] = short_id[i] >> 4;
		ret[i+1] = short_id[i] & 0x0F;
	}
	return ret;


}

int main()
{
    int n;
    Short_client * arr;
    char id[9];
    char * phone;

    printf("Please enter the number of clients: ");
    scanf("%d", &n);


    arr = createShortClientArr(n);



    gets(id);
    phone = searchClientByID(arr,n,id);

    if(phone == NULL)
        printf("Can not find client with i.d. %s\n", id);
    else
    {
        printf("The phone number of client i.d. %s is %s\n", id, phone);
        free(phone);
    }

    free(arr);
}
